using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

public partial struct LoadTestSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<BeginSimulationEntityCommandBufferSystem.Singleton>();
        Entity entity = state.EntityManager.CreateEntity();
        state.EntityManager.AddComponentData(entity, new AssetLoadRequest()
        {
            path = "Assets/Resources/Prefabs/tree_leafy_double"
        });
        state.EntityManager.SetName(entity, "AssetLoadRequest");
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>();
        EntityCommandBuffer ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);
        
        foreach (var (loadResultRef, entity) in SystemAPI.Query<RefRO<AssetLoadResult>>().WithEntityAccess())
        {
            NativeArray<Entity> entities = new NativeArray<Entity>(25, Allocator.Temp);
            ecb.Instantiate(loadResultRef.ValueRO.asset, entities);
            for (int i = 0; i < entities.Length; ++i)
            {
                Entity e = entities[i];
                ecb.SetComponent(e, new LocalTransform()
                {
                    Position = new float3(i % 5.0f * 3.0f, 0.0f, math.floor(i / 5.0f) * 3.0f),
                    Rotation = quaternion.identity,
                    Scale = 1.0f
                });
            }
            ecb.DestroyEntity(entity);
        }
        
        state.Dependency.Complete();
    }

    [BurstCompile]
    public void OnDestroy(ref SystemState state)
    {

    }
}